/*
 * Copyright (c) 2009. Silenus Consultoria, S.L.U.
 */
package es.silenus.detecta.task;

import es.silenus.detecta.model.ImportedFile;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;

import java.io.File;


/**
 * Load file.
 *
 * @author <a href="mailto:malonso@silenus-consultoria.es">Mariano Alonso</a>
 *
 * @since 25-ago-2009 17:32:28
 */
public class LoadFileTask extends AbstractTask {
	/**
	 * Logger for this class.
	 */
	private static final Log LOG = LogFactory.getLog(LoadFileTask.class);

	/**
	 * The job launcher.
	 */
	private JobLauncher jobLauncher;

	/**
	 * The job.
	 */
	private Job job;

	/**
	 * Sets the job launcher.
	 *
	 * @param jobLauncher the job launcher.
	 */
	public void setJobLauncher(final JobLauncher jobLauncher) {
		this.jobLauncher = jobLauncher;
	}

	/**
	 * Sets the job.
	 *
	 * @param job the job.
	 */
	public void setJob(final Job job) {
		this.job = job;
	}

	/**
	 * Retrieves the imported file.
	 *
	 * @return the imported file.
	 */
	private ImportedFile getImportedFile() {
		return (ImportedFile)getParameters().get("importedFile");
	}

	/**
	 * Retrieves the file.
	 *
	 * @return the file.
	 */
	private File getFile() {
		return (File)getParameters().get("file");
	}

	/**
	 * Executes the task.
	 */
	protected void executeInternal() {
		ImportedFile importedFile = getImportedFile();

		File file = getFile();

		try {
			// Setup job parameters
			JobParametersBuilder builder = new JobParametersBuilder();

			builder.addString("input.file.name", file.toURI().toURL().toExternalForm());
			builder.addLong("importedFileId", importedFile.getId());

			// run job
			JobExecution execution = jobLauncher.run(job, builder.toJobParameters());
		} catch(Throwable e) {
			LOG.error("Error loading file: " + file.getName(), e);
		} finally {
			if(file != null) {
				if(!file.delete()) {
					file.deleteOnExit();
				}
			}
		}
	}
}
